package com.nowcoder.community.kafka;

import com.alibaba.fastjson.JSONObject;
import com.nowcoder.community.entity.DiscussPost;
import com.nowcoder.community.entity.Event;
import com.nowcoder.community.entity.Message;
import com.nowcoder.community.service.DiscussPostService;
import com.nowcoder.community.service.ElasticSearchService;
import com.nowcoder.community.service.MessageService;
import com.nowcoder.community.util.CommunityConstant;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class EventConsumer implements CommunityConstant {

    private static final Logger logger = LoggerFactory.getLogger(EventConsumer.class);

    @Autowired
    private MessageService messageService;

    @Autowired
    private ElasticSearchService elasticSearchService;

    @Autowired
    private DiscussPostService discussPostService;

    @KafkaListener(topics={TOPIC_COMMENT, TOPIC_LIKE, TOPIC_FOLLOW})
    public void handleEventMessage(ConsumerRecord record) {
        if(record == null || record.value() == null) {
            logger.error("消息内容为空");
            return;
        }
        Event event = JSONObject.parseObject((String)record.value(), Event.class);
        if(event == null) {
            logger.error("消息格式错误");
            return;
        }
        // 发送站内通知
        Message message = new Message();
        // 默认系统用户的id为1
        message.setFromId(SYSTEM_USER_ID);
        message.setToId(event.getEntityUserId());
        message.setConversationId(event.getTopic().toUpperCase());
        message.setCreateTime(new Date());

        Map<String, Object> content = new HashMap<>();
        // 事件的触发者
        content.put("userId", event.getUserId());
        content.put("entityType", event.getEntityType());
        content.put("entityId", event.getEntityId());
        content.put("entityUserId", event.getEntityUserId());
        // 放入event中可能携带的一些其他信息
        if(!event.getData().isEmpty()) {
            content.putAll(event.getData());
        }
        // 将contentMap转化为一个JSON字符串
        message.setContent(JSONObject.toJSONString(content));
        messageService.addMessage(message);
    }

    /**
     * 消费发帖, 置顶, 加精事件
     * @param record
     */
    @KafkaListener(topics = {TOPIC_PUBLISH, TOPIC_TOP, TOPIC_WONDERFUL})
    public void handlePublishEventMessage(ConsumerRecord record) {
        if(record == null || record.value() == null) {
            logger.error("消息内容为空");
            return;
        }
        Event event = JSONObject.parseObject((String)record.value(), Event.class);
        if(event == null) {
            logger.error("消息格式错误");
            return;
        }

        int discussPostId = event.getEntityId();
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);

        if(post == null) {
            logger.error("查询帖子信息失败");
            return;
        }

        elasticSearchService.saveDiscussPost(post);
    }

    @KafkaListener(topics = {TOPIC_DELETE})
    public void handleDeleteMessage(ConsumerRecord record) {
        if(record == null || record.value() == null) {
            logger.error("消息内容为空");
            return;
        }

        Event event = JSONObject.parseObject((String)record.value(), Event.class);
        if(event == null) {
            logger.error("消息格式错误");
            return;
        }

        int discussPostId = event.getEntityId();
        DiscussPost post = discussPostService.findDiscussPostById(discussPostId);

        if(post == null) {
            logger.error("查询帖子信息失败");
            return;
        }

        elasticSearchService.deleteDiscussPost(discussPostId);
    }

}
